/*
 * Copyright (c) 2023-2023 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.system.sys.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.elsfs.cloud.common.controller.ControllerConfig;
import org.elsfs.cloud.common.controller.LogicRepositoryCrudController;
import org.elsfs.cloud.common.core.vo.R;
import org.elsfs.cloud.system.api.dto.co.ChangePasswordCO;
import org.elsfs.cloud.system.api.dto.co.SysUserEditCO;
import org.elsfs.cloud.system.api.dto.qry.SysUserQry;
import org.elsfs.cloud.system.api.dto.vo.UserInfoVO;
import org.elsfs.cloud.system.api.entity.SysUser;
import org.elsfs.cloud.system.sys.manager.SysUserManager;
import org.elsfs.cloud.system.sys.repository.SysUserRepository;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户控制器
 *
 * @author zeng
 */
@RestController
@RequestMapping("/user")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
@RequiredArgsConstructor
@Tag(description = "user", name = "用户管理")
public class SysUserController
    extends LogicRepositoryCrudController<
        SysUser, SysUserQry, SysUserEditCO, SysUserEditCO, SysUserRepository, String> {
  private final ObjectProvider<PasswordEncoder> passwordEncryptorObjectProvider;
  private final SysUserManager sysUserManager;

  @Override
  protected ControllerConfig getConfig() {
    return super.getConfig()
        .list(true)
        .logicPage(true)
        .logicRestore(true)
        .logicRestoreBatch(true)
        .logicDelete(true)
        .logicDeleteBatch(true)
        .editState(true);
  }

  @GetMapping("userInfo")
  @Operation(summary = "获取用户信息", description = "获取用户信息")
  public R<UserInfoVO> userinfo(@RequestParam(required = false, value = "userId") String userId) {
    // userId = userId == null ? SecurityUtils.getUser().getUserId() : userId;
    return R.success(sysUserManager.getUserInfo(userId));
  }

  @Override
  public R<Boolean> add(SysUserEditCO co) {
    sysUserManager.create(co);
    return R.success();
  }

  @Override
  public R<Boolean> edit(SysUserEditCO co) {
    if (!getConfig().edit()) {
      return R.error("不支持修改数据");
    }
    check(co, true);
    sysUserManager.update(co);
    return R.success(true).setMessage("修改成功");
  }

  @Override
  public R<Boolean> removeById(String id) {
    sysUserManager.delete(id);
    return R.success(true).setMessage("删除成功");
  }

  @PutMapping("/changePassword")
  public R<?> changePassword(@RequestBody @Validated ChangePasswordCO co) {
    SysUser user = repository.getUserByUsername(co.getUsername());
    if (user == null) {
      return R.error("用户不存在");
    }
    String encryptPassword =
        passwordEncryptorObjectProvider
            .getIfUnique(PasswordEncoderFactories::createDelegatingPasswordEncoder)
            .encode(co.getPassword());
    user.setPassword(encryptPassword);
    repository.updateById(user);
    return R.success().setMessage("修改成功");
  }
}
